import os

from django.http import FileResponse
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render_to_response, render
from django.utils.safestring import mark_safe
from django_filters.rest_framework import DjangoFilterBackend

from rest_framework import status,viewsets
from rest_framework.filters import SearchFilter,OrderingFilter
from rest_framework.response import Response

from XApiTestServer.models import TestReports
from XApiTestServer.pagination import MyPageNumberPagination
from XApiTestServer.serializers import ReportSerializer
from XApiTestServer.utils.common import *
from XApiTestServer.utils.test_report import *
from XApiTestServer.utils.response import *


import logging


logger = logging.getLogger('XApiTestServer')


def view_report(request, **kwargs):
    report_id = id=kwargs['pk']
    report_file_name = get_report_file_name(report_id)
    return render(request, report_file_name)

def view_sum_report(request, **kwargs):
    report_id = kwargs['pk']
    summary_report_file_name = get_summary_report_file_name(report_id)
    return render(request, summary_report_file_name)

class ReportViewSet(viewsets.ModelViewSet):
    queryset = TestReports.objects.all()
    serializer_class = ReportSerializer
    pagination_class = MyPageNumberPagination
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    search_fields = ('report_name',)
    ordering_fields = ('update_time', )


    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        report_index = instance.id
        logger.info("View Report Index:{}".format(report_index))
        report_name = TestReports.objects.get(id=report_index).reports
        report_path = os.path.join(settings.BASE_DIR, "reports", report_name)
        if not os.path.exists(report_path):
            return Response(REPORT_NOT_EXISTS, status=status.HTTP_201_CREATED)

        with io.open(report_path, 'r', encoding='utf-8') as stream:
            reports = stream.read()

        return render_to_response('view_report.html', {"reports": mark_safe(reports)})


    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        try:
            report_index = instance.id
            report_name = TestReports.objects.get(id=report_index).reports
            report_path = os.path.join(settings.BASE_DIR, "reports", report_name)
            logger.info("Delete Report Index:{}".format(report_index))
            self.perform_destroy(instance)
            if os.path.exists(report_path):
                os.remove(report_path)
        except ObjectDoesNotExist:
            return Response(FILE_NOT_EXISTS, status=status.HTTP_201_CREATED)

        response_body = SUCCESS_DEL
        return Response(response_body)


    def reportdownload(self, request, *args, **kwargs):
        instance = self.get_object()

        report_index = instance.id
        report_name = TestReports.objects.get(id=report_index).reports
        report_path = os.path.join(settings.BASE_DIR, "reports", report_name)
        logger.info("Download Report Index:{}".format(report_index))
        if not os.path.exists(report_path):
            return Response(FILE_NOT_EXISTS, status=status.HTTP_201_CREATED)
        response = FileResponse(open(report_path, 'rb'))
        response['Content-Type'] = 'application/octet-stream'

        return response
